package com.xcesys.extras.remoting.system.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xcesys.extras.core.service.ICrudService;
import com.xcesys.extras.dataobject.system.Resource;
import com.xcesys.extras.dataobject.system.Role;
import com.xcesys.extras.dataobject.system.User;
import com.xcesys.extras.model.TsResource;
import com.xcesys.extras.model.TsRole;
import com.xcesys.extras.model.TsUser;
import com.xcesys.extras.remoting.BaseRemotingServiceCrudImpl;
import com.xcesys.extras.remoting.system.RUserService;
import com.xcesys.extras.system.service.TsUserService;

@Service("RUserService")
public class RUserSerivceImp extends BaseRemotingServiceCrudImpl<User, TsUser>
		implements RUserService {

	@Autowired
	private TsUserService service;

	@Override
	public void addRolesToUser(Long userId, List<Long> roles) {
		service.addRolesToUser(userId, roles);
	}

	@Override
	public List<Resource> findResourceInUser(Long userId) {
		List<TsResource> res = new ArrayList<TsResource>();
		TsUser users = service.findById(userId);
		if (users != null) {
			Set<TsRole> roles = users.getTsRoles();
			if (roles != null && !roles.isEmpty()) {
				for (TsRole role : roles) {
					res.addAll(role.getTsResources());
				}
			}
		}
		return (List<Resource>) fromModel(Resource.class, res);
	}

	@Override
	public List<Role> findRolesInUser(Long userId) {
		TsUser tsUser = service.findById(userId);
		if (tsUser == null)
			return null;
		Collection<TsRole> tsRoles = tsUser.getTsRoles();
		List<TsRole> roles = new ArrayList<TsRole>();
		roles.addAll(tsRoles);
		return (List<Role>) fromModel(Role.class, roles);
	}

	@Override
	protected ICrudService<TsUser> getCrudService() {
		return service;
	}

	@Override
	public void removeRolesFromUser(Long userId, List<Long> roleIds) {
		service.removeRolesFromUser(userId, roleIds);
	}

	@Override
	public void lock(List<Long> ids) {
		service.lockUsers(ids, true);
	}

	@Override
	public void unlock(List<Long> ids) {
		service.lockUsers(ids, false);
	}

	@Override
	public void resetPassword(List<Long> ids) {
		service.resetPassword(ids);
	}
}
